﻿using ItemSystem.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ItemSystem.Controllers
{
    public class AddItemController : ApiController
    {
        public EFContext context = new EFContext();

        [HttpPost]
        public IHttpActionResult AddItem(JObject jobj)
        {
            if (jobj == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("JSON对象为空") });
            }
            var szname = jobj.Value<string>("name");
            var szusage = jobj.Value<string>("usage");
            if (szname == null
                || szusage == null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("物品内容缺失") });
            }
            var newItem = new Item()
            {
                name = szname,
                usage = szusage,
                isStoring = false
            };
            context.items.Add(newItem);
            context.SaveChanges();
            return Ok(newItem.id);
        }
    }
}
